package com.ruike.alisurface.mqtt;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.SystemClock;

import com.ruike.alisurface.BuildConfig;
import com.ruike.alisurface.Constant;
import com.ruike.alisurface.MyApplication;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.Serials.ShopInfoUtils;
import com.ruike.alisurface.Serials.Ttys3Utils;
import com.ruike.alisurface.Serials.outGoods.ShengJiangJiUtils;
import com.ruike.alisurface.Serials.outGoods.ShopChUtils;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.advBean;
import com.ruike.alisurface.bean.lockBean;
import com.ruike.alisurface.http.AdvdataHttp;
import com.ruike.alisurface.http.MchApiHttp;
import com.ruike.alisurface.services.MyFileVedioService;
import com.ruike.alisurface.services.MyScrennService;
import com.ruike.alisurface.services.NetWorkListenerService;
import com.ruike.alisurface.ui.mainPage.SystemStartActivity;
import com.ruike.alisurface.ui.mainPage.VedioAdvActivity;
import com.ruike.alisurface.utils.AlogHttpUtils;
import com.ruike.alisurface.utils.BackMainUtils;
import com.ruike.alisurface.utils.DeviceUtils;
import com.ruike.alisurface.utils.MYUtiles;
import com.ruike.alisurface.utils.ShareKey;
import com.ruike.alisurface.utils.ThreadUtils;
import com.voodoo.lib_frame.base.BaseView;
import com.voodoo.lib_frame.manager.FActivityManager;
import com.voodoo.lib_utils.GsonUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.NetUtil;
import com.voodoo.lib_utils.ShareUtils;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static com.ruike.alisurface.mqtt.MQTTService.mqttClient;
import static com.ruike.alisurface.utils.ShareKey.BASEUSERID;
import static com.ruike.alisurface.utils.ShareKey.SERVICE_TEL;
import static com.ruike.alisurface.utils.ShareKey.Type_Chshopzl;
import static com.ruike.alisurface.utils.ShareKey.Type_Chshopzl_OLD;
import static com.ruike.alisurface.utils.ShareKey.Type_Lockclose;
import static com.ruike.alisurface.utils.ShareKey.Type_Lockopen;
import static com.ruike.alisurface.utils.ShareKey.Type_Steal;


/**
 * Author: voodoo
 * CreateDate: 2020-04-02 002 下午 08:00
 * Description: Mqtt操作类
 */
public class MqttOperation implements Ttys3Utils.Serial3CallBack {

    public static final String Tag = "Mqtt操作类==";
    public static int connectNumber; // 连接次数

    public Context context;
    public Handler handler;
    public int mqttLinkReturnCount = 0; // Mqtt链接回调次数，以控制日志打印


    public MqttOperation(Context context) {
        this.context = context;
        Ttys3Utils.getInstance().setSerial3CallBack(this);
    }

    /**
     * 订阅各个主题screenshots
     *
     * @param mqttClient Android链接
     * @throws MqttException MqttException
     */
    public void subscribeToTopic(MqttAndroidClient mqttClient) throws MqttException {
        mqttClient.subscribe(Constant.Mqtt.SUBSCR_ADVERTISEMENT, 2); // 广告下发
        mqttClient.subscribe(Constant.Mqtt.SUBSCR_LANE_UPDATA, 2); // 货道更新
        mqttClient.subscribe(Constant.Mqtt.SUBSCR_OUT_GOODS, 2); // 远程出货
        mqttClient.subscribe(Constant.Mqtt.SUBSCR_CMD, 2); // 远程获取日志
        mqttClient.subscribe(Constant.Mqtt.SUBSCR_TEMPERATURE_CONTROL, 2); // 温度控制
        mqttClient.subscribe(Constant.Mqtt.SUBSCR_OUTADV, 2); // 售货机接收广告推送
        mqttClient.subscribe(Constant.Mqtt.SUBSCR_LOCK, 2); // 售货机电控锁
        mqttClient.subscribe(Constant.Mqtt.BINDSUSCCESS, 2); // 售货机接收绑定重启软件
        mqttClient.subscribe(Constant.Mqtt.SERVICE_TEL, 2); // 售货机接收更新机主电话
        mqttClient.subscribe(Constant.Mqtt.SUBSCR_GET_OPENID, 2); // 获取扫码关注公众号人的 OpenId

    }

    /**
     * Mqtt 回传消息处理
     *
     * @param topic 订阅的主题
     * @param body  回传的消息字符串
     * @throws JSONException 回传消息Json转换异常
     */
    public void processMsg(String topic, String body) throws JSONException {
        JSONObject bodyJson = new JSONObject(body);
        if (topic.equals(Constant.Mqtt.SUBSCR_GET_OPENID)) { // 获取扫码关注公众号人的 OpenId
            if ("question_login".equals(bodyJson.getString("action"))) {
                String openId = bodyJson.getString("openid");
                ShareUtils.getInstance().putString(ShareKey.QUESTION_UID, openId);
                EventBus.getDefault().post(new MsgEventBus("AnswerQuestionLogin", openId));
            }
            return;
        }
        if (topic.equals(Constant.Mqtt.SUBSCR_ADVERTISEMENT)) { // 广告下发
            return;
        }
        if (topic.equals(Constant.Mqtt.SUBSCR_LANE_UPDATA)) { // 货道更新
            return;
        }
        if (topic.equals(Constant.Mqtt.SUBSCR_OUT_GOODS)) { // 远程出货
            ShopGoods(body);
            return;
        }
        if (topic.equals(Constant.Mqtt.SUBSCR_CMD)) { // 远程获取日志或截屏
            getSUBSCR_CMD(bodyJson);
            return;
        }
        if (topic.equals(Constant.Mqtt.SUBSCR_TEMPERATURE_CONTROL)) { // 温度灯光控制
            if (Constant.showShop) {
                L.i("远程出货中，不可设置温控");
                return;
            }
            getTemperature_Light(body);
            return;
        }
        if (topic.equals(Constant.Mqtt.SUBSCR_OUTADV)) { // 售货机接收广告推送
            UploadAdv(bodyJson);
            return;
        }
//
//        Topic:rkt/mch/{SN}/lock/
//                {"msgid": "01234567890123456789_lock","ElecEn":1,"ElecNum":0,"ElecOnTi":10,"ElecState":1,"boxno":0}
//        msgid:用于标记服务器发来消息的序列号。
//        ElecEn：电磁锁使能标志，0-关闭此功能，1-开启此功能，在0的状态下，所有设置无效。
//        ElecNum：需要打开哪个电磁锁，0表示1通道，1表示2通道
//        ElecOnTi：电磁锁通电时间，取值3-50，对应0.3s-5s
//        ElecState：对应通道电磁锁的状态，0表示没有通电，1表示已通电。
//        boxno:货柜编号 0是主柜 其余递推


        if (topic.equals(Constant.Mqtt.SUBSCR_LOCK)) { //售货机电控锁  门
            sendDoor(bodyJson);
            return;
        }

        if (topic.equals(Constant.Mqtt.BINDSUSCCESS)) { // 售货机接收绑定重启软件
            todoBINDSUSCESS(bodyJson);
            return;
        }
        if (topic.equals(Constant.Mqtt.SERVICE_TEL)) { //  更新机主电话
            if (DeviceUtils.getDeviceSn().equals(bodyJson.optString("sn"))) {
                String service_tel = bodyJson.optString("service_tel");
                if (!service_tel.equals("null") && service_tel != null && !service_tel.isEmpty()) {
                    L.i("===service_tel==" + service_tel);
                    ShareUtils.getInstance().putString(SERVICE_TEL, service_tel);
                } else {
                    ShareUtils.getInstance().putString(SERVICE_TEL, context.getString(R.string.noPhoneStr));
                }
                EventBus.getDefault().post(new MsgEventBus(SERVICE_TEL, service_tel));
            }
            return;
        }
    }

    /**
     * 售货机接收绑定重启软件
     *
     * @param bodyJson
     */
    private void todoBINDSUSCESS(JSONObject bodyJson) {

        String sn = bodyJson.optString("sn");
        if (sn.equals(DeviceUtils.getDeviceSn())) {
            L.i("绑定成功 重新启动");
            ShareUtils.getInstance().putString(BASEUSERID, "RK");
            ThreadUtils.postUI(new Runnable() {
                @Override
                public void run() {
                    ((BaseAty) FActivityManager.getInstance().getTopActivity()).startCountdownTimer(0, null, null);
                }
            });

        }
    }


    public void sendDoor(JSONObject bodyJson) {

        L.i(" 解析开锁mqtt 信息");
        try {
            int ElecEn = bodyJson.getInt("ElecEn");
            int ElecNum = bodyJson.getInt("ElecNum");
            int ElecOnTi = bodyJson.getInt("ElecOnTi");
            int ElecState = bodyJson.getInt("ElecState");
            int boxno = bodyJson.getInt("boxno");
            String msgid = bodyJson.getString("msgid");
            L.i("msgid", msgid, "boxno", boxno);
//            ShareUtils.getInstance().putString(LOCK_MSGID, msgid);

            List<lockBean> locklist = MyApplication.finalDbUtils.findAllByWhere(lockBean.class, " boxno = " + boxno);
            if (locklist != null && locklist.size() > 0) {
                locklist.get(0).setMsgid(msgid);
                MyApplication.finalDbUtils.update(locklist.get(0));
            } else {
                lockBean lockBean = new lockBean();
                lockBean.setBoxno(boxno);
                lockBean.setMsgid(msgid);
                MyApplication.finalDbUtils.save(lockBean);
            }
            Ttys3Utils.getInstance().DoorSetting(boxno, ElecOnTi, ElecNum);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 远程获取日志 或截屏信息
     */

    public void getSUBSCR_CMD(JSONObject bodyJson) {

        if (bodyJson.optString("action").equals("pulllog")) {
            String begin = bodyJson.optString("begin");
            String end = bodyJson.optString("end");
            L.i(Tag + "messageArrived: 上传日志" + begin + "--" + end);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    AlogHttpUtils.upodataLog(begin, end);
//                        DeleteLog.upodataCrashLog(getBaseContext());
                }
            }).start();

            return;
        } else if (bodyJson.optString("action").equals("screenshots")) {

            L.i(Tag + " 截图 screenshots");
            ShareUtils.getInstance().putString("cmd_id", bodyJson.optString("cmd_id"));
            Intent intent = new Intent(MyApplication.getAppContext(), MyScrennService.class);
            MyApplication.getAppContext().startService(intent);

            return;
        }
    }


    /**
     * 接收推送来的广告列表
     *
     * @param jsonobject
     */
    private void UploadAdv(JSONObject jsonobject) {
        try {
            String ad_id = jsonobject.getString("ad_id");
            int ad_type = jsonobject.getInt("ad_type"); // 广告类型 0图片 1视频
            String r_list = jsonobject.getString("r_list"); // 数据列表
            JSONArray jsarrry = new JSONArray(r_list);
            //获得当前运行的task
            Activity topActivity = FActivityManager.getInstance().getTopActivity();
            //找到当前应用的task，并启动task的栈顶activity，达到程序切换到前台
            if (topActivity.getPackageName().equals(BuildConfig.APPLICATION_ID)) {

                if (topActivity.getLocalClassName().contains("VedioAdvActivity")) {
                    L.i("栈顶activity   333:" + topActivity.getLocalClassName());
                    if (ad_type == Constant.ADV_TYPE_NONE) {
                        ShareUtils.getInstance().putInt(ShareKey.ADV_TYPE, Constant.ADV_TYPE_NONE);
                        Intent intent = BackMainUtils.setActivity(context);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intent);

                        AdvdataHttp.getConfirm_ApplyAd(ad_id, baseView);
                        return;
                    }

                } else if (topActivity.getLocalClassName().contains("MainActivity") || topActivity.getLocalClassName().contains("MainTypeActivity")) {
                    if (ad_type == Constant.ADV_TYPE_NONE) {
                        AdvdataHttp.getConfirm_ApplyAd(ad_id, baseView);
                        return;
                    }
                    if (ad_type == Constant.ADV_TYPE_IMAGE) {
                        ShareUtils.getInstance().putInt(ShareKey.ADV_TYPE, Constant.ADV_TYPE_IMAGE);
                    } else if (ad_type == Constant.ADV_TYPE_VIDEO) {
                        ShareUtils.getInstance().putInt(ShareKey.ADV_TYPE, Constant.ADV_TYPE_VIDEO);
                    }
                    Intent intent = new Intent(context, VedioAdvActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);

                } else {
                    ShareUtils.getInstance().putInt(ShareKey.ADV_TYPE, ad_type);
                }
            }
            L.i(Tag + "在广告页 ");
//            ALog.i("jsarrry===" + jsarrry);
            if (ad_type == 0) {

                L.i(Tag + "图片样式 ");
                EventBus.getDefault().post(new MsgEventBus("adv_type", "图片样式"));
                ShareUtils.getInstance().putInt(ShareKey.ADV_TYPE, Constant.ADV_TYPE_IMAGE);
                MyApplication.finalDbUtils.deleteByWhere(advBean.class, " types = '0'");
                for (int i = 0; i < jsarrry.length(); i++) {
                    advBean ab = new advBean();
                    ab.setUrl(jsarrry.getJSONObject(i).getString("url"));
                    ab.setSort(jsarrry.getJSONObject(i).getInt("sort"));
                    ab.setTypes("0");
                    MyApplication.finalDbUtils.save(ab);
                    if (i == jsarrry.length() - 1) {
                        EventBus.getDefault().post(new MsgEventBus("adv", "图片下载成功"));
                        break;
                    }
                }
            } else if (ad_type == 1) {
                L.i(Tag + "视频样式 ");
                EventBus.getDefault().post(new MsgEventBus("vedio_type", "视频样式"));
                ShareUtils.getInstance().putInt(ShareKey.ADV_TYPE, Constant.ADV_TYPE_VIDEO);
                MyApplication.finalDbUtils.deleteByWhere(advBean.class, " types = '1'");
                for (int i = 0; i < jsarrry.length(); i++) {
                    advBean ab = new advBean();
                    ab.setUrl(jsarrry.getJSONObject(i).getString("url"));
                    ab.setSort(jsarrry.getJSONObject(i).getInt("sort"));
                    ab.setTypes("1");
                    MyApplication.finalDbUtils.save(ab);
                    if (i == jsarrry.length() - 1) {
                        Intent intent = new Intent(MyApplication.getAppContext(), MyFileVedioService.class);
                        MyApplication.getAppContext().startService(intent);
                        break;
                    }
                }
            }
            AdvdataHttp.getConfirm_ApplyAd(ad_id, baseView);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置温控及灯
     */
    public void getTemperature_Light(String body) {
        try {
            Constant.isSzwk = true;
            JSONObject jsonObject = new JSONObject(body);
            if (body.contains("temauto")) {
                // :{"msgid":"38a99cfc-a1b8-42d6-af05-6caef7b36498","temauto":"020001000A3C0201010000FF01"}
                String tem = jsonObject.getString("temauto");
                L.i(Tag + "我是温控指令 messageArrived: =======tem===" + tem);
                String tems = "23" + "0E" + tem;
                int ssum = MYUtiles.subString(tems);
                String h = Integer.toHexString(ssum);
                String fff = h.substring(h.length() - 2).toUpperCase();
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(tems).append(fff);
                String Ssend = stringBuilder.toString();
                L.i(Tag + "messageArrived: Send===" + Ssend);

                Ttys3Utils.getInstance().SendPort(Ssend);

            } else {
                L.i(Tag + "messageArrived: ----我是灯光指令");
                // : MQTT收到:{"msgid":"6b22ed1b-e079-42e7-a152-71eaa12da024","LEDMode":1,"LEDOnOff":0,"LEDMax":20,"LEDTime":"1","LEDstate":1}
                String LEDMode = jsonObject.getString("LEDMode");
                String LEDOnOff = jsonObject.getString("LEDOnOff");
                String LEDMax = jsonObject.getString("LEDMax");
                String LEDTime = jsonObject.getString("LEDTime");
                String LEDstate = jsonObject.getString("LEDstate");
                int light = Integer.parseInt(LEDMax);
                int time = Integer.parseInt(LEDTime);
                // 发送灯光命令
                Ttys3Utils.getInstance().LEDSetting(10, LEDMode, "1", LEDOnOff, light, time);
                Thread.sleep(500);
                Ttys3Utils.getInstance().LEDSetting(11, LEDMode, "1", LEDOnOff, light, time);
                Thread.sleep(500);
                Ttys3Utils.getInstance().LEDSetting(12, LEDMode, "1", LEDOnOff, light, time);
                Thread.sleep(500);

            }

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            Constant.isSzwk = false;
            L.i(Tag + "       Constant.isSzwk===" + Constant.isSzwk);
        }
    }

    private String oid_id = "-1";

    /**
     * 远程出货
     *
     * @param str1 发布的消息信息
     */
    private void ShopGoods(String str1) {
        /*
         {
         "oid": "2018112114100000022518",//订单号
         "odc": 5,
         "od": "042010|042010|042010|042010|042010|042010|042010",//出货的货道、数量、类型
         "ot": 201
         |042010|042010|042010|042010|042010|042010
         String str1 = " {\n" +
         "         \"oid\": \"2018112114100000022518\",//订单号\n" +
         "         \"odc\": 5,\n" +
         "         \"od\": \"042010|042010|042010|042010|042010|042010|042010\",//出货的货道、数量、类型\n" +
         "         \"ot\": 201\n" +
         "         }";
         }
         */
        try {
            JSONObject jsonobject = new JSONObject(str1);
            String oid = jsonobject.getString("oid");
            if (oid_id.equals(oid)) {
                L.i(Tag + "远程出货oid 相同 ----oid:" + oid, "-----oid_id:" + oid_id);
                return;
            }
            String ot = jsonobject.getString("ot");
            String od = jsonobject.getString("od");
            L.i(Tag + "----oid:" + oid, "-----ot:" + ot, "-----od:" + od);
            if (ot.equals("202") || ot.equals("204")) {
                oid_id = oid;
                Constant.showShop = true;
                if (od.contains("|")) {
                    String[] d = od.split("\\|");
                    for (int i = 0; i < d.length; i++) {
                        L.i(Tag + "aa: ----hahah---" + d[i]);
                        String data = d[i];
                        if (data.length() == 6) {
                            String index = data.substring(0, 3);
                            String num = data.substring(3, 5);
                            String type = data.substring(5, 6);
                            int number = Integer.parseInt(num);
                            L.i(Tag + "----index:" + index + "-----num:" + num + "-----type:" + type);
                            setgetShop(number, Integer.parseInt(index), Integer.parseInt(type));
                        } else {
                            L.i(Tag + " 接收的数据出现错误 " + d);
                        }
                    }
                } else {
                    L.i(Tag + "aa: --不包含多个货道信息");
                    String index = od.substring(0, 3);
                    String num = od.substring(3, 5);
                    String type = od.substring(od.length() - 1);
                    int number = Integer.parseInt(num);
                    L.i(Tag + "----index:" + index + "-----num:" + number + "-----type:" + type);
                    setgetShop(number, Integer.parseInt(index), Integer.parseInt(type));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            L.i(Tag + "ResiveDate: 接收数据错误" + e);
        } finally {
            Constant.showShop = false;
            L.i(Tag + " Constant.showShop===" + Constant.showShop);
        }
    }

    int countNum = 0;
    boolean isMQTTshop;

    public void setgetShop(int number, int index, int indextype) {
        isMQTTshop = true;
        countNum = number;
        int slottype = 21001;
        if (indextype == 0) {
            slottype = 21001;
        } else if (indextype == 1) {
            slottype = 21001;
        } else if (indextype == 2) {
            slottype = 21002;
        }
        L.i(Tag + "----index:" + index + "-----number:" + number + "-----type:" + slottype);
        if (Constant.machineType == 1) { // IC2
            for (int i = 0; i < number; i++) {
                ShopChUtils.shopTodo(slottype, index);
                --countNum;
            }
        } else if (Constant.machineType == 2) { // 升降机
            ShengJiangJiUtils.setOnSJJListener(new ShengJiangJiUtils.OnSJJOutGoodsListener() {
                @Override
                public void outGoodsSuccess() {
                }

                @Override
                public void outGoodsFailure(String msg) {
                }
            });
            ShengJiangJiUtils.outGoods(index, slottype);
        }
    }


    public BaseView baseView = new BaseView() {
        @Override
        public void onStarted(String loadingStr) {

        }

        @Override
        public void onLoading(long total, long current) {

        }

        @Override
        public void onComplete() {

        }

        @Override
        public void onErrorTip(String errorStr) {

        }

        @Override
        public void onSuccess(String requestUrl, String requestJsonStr) {
            L.i(Tag + "onSuccess    requestUrl===" + requestUrl, "==requestJsonStr==" + requestJsonStr);
        }

        @Override
        public void onFailure(String requestUrl, String requestMsg) {

        }

        @Override
        public void onError(String requestUrl, String errorMsg) {
            L.i(Tag + "onError   requestUrl===" + requestUrl, "==errorMsg==" + errorMsg);
        }

        @Override
        public void onException(Exception exception) {

        }

        @Override
        public void onDownloadSuccess(String requestUrl, File file) {

        }

        @Override
        public void onDownloading(String requestUrl, int progress) {

        }

        @Override
        public void onDownloadFailed(String requestUrl, Exception e) {

        }
    };


    /**
     * 每十秒钟查询mqtt是否在线，如果不在线就连接
     */
    public void ConnectMqtt(MqttConnectOptions mqttConnectOptions, IMqttActionListener callback) {
        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                isTimeMqtt(mqttConnectOptions, callback);
            }
        };
        timer.schedule(timerTask, 0, 10000);
    }

    private void isTimeMqtt(MqttConnectOptions mqttConnectOptions, IMqttActionListener callback) {
        try {
            if (mqttClient == null) {
                return;
            }
            if (!isConnectNet()) { // 判断网络是否连接
                L.i("mqtt 网络未连接 ");
                return;
            }
            if (!mqttClient.isConnected()) {
                L.i("mqtt 尝试连接中 ");
                mqttClient.connect(mqttConnectOptions, null, callback);
                connectNumber++;
                try { // 连接3次之后，没有连上就重启机器
//                                if (connectNumber >= 3 && !tmpflg) {
                    if (connectNumber >= 3) {
                        L.i("重连失败，重启APP... " + connectNumber);
                        // 重启app
                        Intent intent = new Intent(context, SystemStartActivity.class);
                        @SuppressLint("WrongConstant")
                        PendingIntent restartIntent = PendingIntent.getActivity(
                                context, 0, intent,
                                Intent.FLAG_ACTIVITY_NEW_TASK);
                        AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
                        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 3000, restartIntent);
                        FActivityManager.getInstance().killAllActivityExit();
                    }
                } catch (Exception e) {
                    L.e("判断链接重启异常：" + e.toString());
                    e.printStackTrace();
                }
            } else {
                if (mqttLinkReturnCount++ >= 10) {
                    L.i("mqtt 在线 ");
                    mqttLinkReturnCount = 0;
                }
                connectNumber = 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    int wk = 0, jd = 0, yxlx = 0;
    String data = null;
    String data1 = null;
    String data2 = null;
    String type = null;
    HandlerThread handlerThread;

    public void getHandle() {
        handlerThread = new HandlerThread("HandlerThread");
        handlerThread.start();
        handler = new Handler(handlerThread.getLooper()) {
            // 使用handleMessage去处理消息！！，里面的参数Message msg既是发送过来的参数~
            @Override
            public void handleMessage(android.os.Message msg) {
                if (msg.what == 0x01) {
                    if (data == null && type == null) {
                        wk++;
                        if (wk < 3) {
                            L.i("循环发送updateTemp: data1：=" + wk);
                            Ttys3Utils.getInstance().SendPort("230303032C");
                            ThreadUtils.postDelayed(BeatXh, 1500);
                        } else {
                            pushBeat();
                        }
                    } else if (data1 == null && type != null && type.equals("01")) {
                        jd++;
                        if (jd < 3) {
                            L.i("循环发送updateTemp: data2：=" + jd);

                            Ttys3Utils.getInstance().SendPort("230303042D");
                            ThreadUtils.postDelayed(BeatXh, 1500);
                        } else {
                            pushBeat();
                        }
                    } else if (data2 == null && type != null && type.equals("02")) {

                        yxlx++;
                        if (yxlx < 3) {
                            L.i("循环发送updateTemp: data3：=" + yxlx);

                            Ttys3Utils.getInstance().SendPort("230303052E");
                            ThreadUtils.postDelayed(BeatXh, 1500);
                        } else {
                            pushBeat();
                        }
                    }

                } else if (msg.what == 0x02) {
                    Beat();
                }
            }
        };
    }


    /**
     * 发送开启电控锁 返回值
     * Topic:rkt/lockrespond/
     * {"msgid":"01234567890123456789_lock","lockinit": 2,"doorinit": 2,"locknow": 2,"doornow": 2}
     *
     * @param date
     * @return
     */
    public void LockOpenDoor(String date) {
        String[] data_code = date.split(" ");
        if (data_code.length < 8) {
            L.i("发送电控锁 数据失败  ，数据不完整");
            return;
        }
        int lockinit = Integer.parseInt(data_code[3]);
        int doorinit = Integer.parseInt(data_code[4]);
        int locknow = Integer.parseInt(data_code[5]);//，1-关闭，2-开启
        int doornow = Integer.parseInt(data_code[6]);//，1-关闭，2-开启

        int opendoor = Integer.parseInt(data_code[7]);//00-IC2主柜
        int locktype = Integer.parseInt(data_code[8]);// 00-机械开锁，01-电控开锁

        HashMap<String, Object> map = new HashMap<>();

        if (locktype == 1) {
            List<lockBean> locklist = MyApplication.finalDbUtils.findAllByWhere(lockBean.class, " boxno = " + opendoor);
            if (locklist != null && locklist.size() > 0) {
                map.put("msgid", locklist.get(0).getMsgid());
                map.put("lockinit", lockinit);
                map.put("doorinit", doorinit);
            }
        }
        map.put("sn", DeviceUtils.getDeviceSn());
        map.put("locknow", locknow);
        map.put("doornow", doornow);
        map.put("boxno", opendoor);
        map.put("opentype", locktype);
        String data = GsonUtils.StringMapToJson(map);
        L.i(" 发送电控锁 上传数据===" + data);
        if (locknow == 2) {
//            Topic:rkt/lockrespond/
//{"msgid":"01234567890123456789_lock","sn":"999999999","lockinit": 2,"doorinit": 2,"locknow": 2,"doornow": 2,"boxno":0}
            publishMessage("rkt/lockrespond/", data);
        }

    }

    /**
     * 发送关闭电控锁 返回值
     * Topic:rkt/lockrespond/
     * {"msgid":"01234567890123456789_lock","lockinit": 2,"doorinit": 2,"locknow": 2,"doornow": 2}
     *
     * @param date
     * @return
     */
    public void LockCloseDoor(String date) {
        String[] data_code = date.split(" ");
        if (data_code.length < 6) {
            L.i("上传 关闭电控锁 数据失败  ，数据不完整");
            return;
        }
        int locknow = Integer.parseInt(data_code[3]);//，1-关闭，2-开启
        int doornow = Integer.parseInt(data_code[4]);//，1-关闭，2-开启

        int opendoor = Integer.parseInt(data_code[5]);//00-IC2主柜
        int locktype = Integer.parseInt(data_code[6]);// 00-机械关锁，01-电控关锁

        HashMap<String, Object> map = new HashMap<>();

        List<lockBean> locklist = null;
        if (locktype == 1) {
            locklist = MyApplication.finalDbUtils.findAllByWhere(lockBean.class, " boxno = " + opendoor);
            if (locklist != null && locklist.size() > 0) {
                map.put("msgid", locklist.get(0).getMsgid());
            }
        }
        map.put("sn", DeviceUtils.getDeviceSn());
        map.put("locknow", locknow);
        map.put("doornow", doornow);
        map.put("boxno", opendoor);
        map.put("opentype", locktype);

        String data = GsonUtils.StringMapToJson(map);
        L.i(" 发送电控锁 上传数据===" + data);

        if (locknow == 1) {  //关闭
//            Topic:rkt/closelockrespond/
//                    {"msgid":"01234567890123456789_lock","sn":"999999999","lockclose": 2,"doorclose": 2,"boxno":0,"opentype":1}
            publishMessage("rkt/closelockrespond/", data);

        }

        if (locktype == 1) {
            if (locklist != null && locklist.size() > 0) {
                L.i(" locklist  删除msgid ");
                MyApplication.finalDbUtils.delete(locklist.get(0));
            }
        }
    }


    /**
     * 发送后台偷盗指令
     * Topic：rkt/msgrespond/
     * 报文：{
     * "sn":"868821045734076","droptype":"1","dropno":1
     * }
     */
    public void sendSteal(String date) {
        String[] data_code = date.split(" ");
        if (data_code.length < 3) {
            L.i("上传偷盗指令 数据失败  ，数据不完整");
            return;
        }
        HashMap<String, Object> map = new HashMap<>();
        int dropno = Integer.parseInt(data_code[3]);//，1-关闭，2-开启
        map.put("sn", DeviceUtils.getDeviceSn());
        map.put("dropno", dropno);
        map.put("droptype", "1");
        String data = GsonUtils.StringMapToJson(map);
        publishMessage("rkt/msgrespond/", data);
    }

    private String getMesg(String msg) {
        String date = msg.replaceAll(" ", "");
        if (date.equals("")) {
            return null;
        }
        String strm = date.substring(0, date.length() - 2);
        return truncateHeadString(strm, 4);
    }

    public String truncateHeadString(String origin, int count) {
        if (origin == null || origin.length() < count) {
            return null;
        }
        char[] arr = origin.toCharArray();
        char[] ret = new char[arr.length - count];
        for (int i = 0; i < ret.length; i++) {
            ret[i] = arr[i + count];
        }
        return String.copyValueOf(ret);
    }

    /**
     * 上传温湿度信息
     */
    private void Beat() {
        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                try {
                    MchApiHttp.getSignal_Intensity(baseView, BaseAty.signalStrength);
                } catch (Exception e) {
                    L.i("mqtt 上传网络信号异常 ");
                }
                L.i("mqtt: 是否开始温度信息查询=" + Constant.showShop + "--mqtt 在线状态--" + isConnected());
                if (!Constant.showShop && !Constant.isSzwk) {
                    handler.removeCallbacksAndMessages(null);
                    updateBeatTemp();
                }
            }
        };
        timer.schedule(timerTask, 10, 250000);
    }

    /**
     * 上传温度湿度继电器状态等信息
     * 250s更新一次
     */
    String heart;
    Runnable BeatXh = new Runnable() {
        @Override
        public void run() {
//            handler.sendEmptyMessage(0x01);
        }
    };

    private void updateBeatTemp() {
        heart = "rkt/mch/heart/";
        try {
            data = null;
            data1 = null;
            data2 = null;
            type = null;
            wk = 0;
            jd = 0;
            yxlx = 0;
            Ttys3Utils.getInstance().SendPort("230303032C");
            handler.removeCallbacksAndMessages(null);
            handler.postDelayed(BeatXh, 1500);
        } catch (Exception e) {
            e.printStackTrace();
            L.i("updateTemp: " + e);
        }
    }

    /**
     * 心跳信息的温控值 继电器  运行类型 发送
     */
    public void pushBeat() {
        if (mqttClient == null) {
            return;
        }
        if (!mqttClient.isConnected()) {
            return;
        }
        try {
            if (data == null || data1 == null || data2 == null) {

                L.i("updateTemp: 温控数据有值返回位null", data + "--", data1 + "---", data2);
            } else {
                StringBuilder sb = new StringBuilder();
                String lastDate = sb.append(data).append(data1).append(data2).toString();
                String msg = "{\"temid\": \"" + DeviceUtils.getDeviceSn() + "\"," + "\"temhum\": \"" + lastDate + "\"" + "}";
                if (mqttClient != null) {
                    L.i("====updateTemp: " + msg);
                    mqttClient.publish(heart, msg.getBytes(), 2, false);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取网络是否连接
     */
    private boolean isConnectNet() {
        int isConnect = NetUtil.getNetWorkState(context);
        return isConnect == 0 || isConnect == 1;
    }

    public boolean isConnected() {

        if (mqttClient != null) {
            return mqttClient.isConnected();
        }
        return false;
    }

    public static void publishMessage(String topic, final String msg) {
        try {
            MqttMessage message = new MqttMessage();
            message.setPayload(msg.getBytes());
            mqttClient.publish(topic, message, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    L.i("publish--", "success:" + msg);
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    L.i("publish--", "failed:" + msg);
                }
            });
        } catch (MqttException e) {
            L.e("publish---", "exception", e);
        }
    }

    @Override
    public void onSerialPortData(String type, String serialPortData) {
        if (!Constant.showShop && !Constant.isSzwk) {
            if (type.equals("01")) {
                data = getMesg(serialPortData);
                L.i("updateTemp: data1：" + data);
                Ttys3Utils.getInstance().SendPort("230303042D");
                return;
            } else if (type.equals("02")) {
                data1 = getMesg(serialPortData);
                L.i("updateTemp: dat:2：" + data1);
                Ttys3Utils.getInstance().SendPort("230303052E");
                return;
            } else if (type.equals("03")) {
                data2 = getMesg(serialPortData);
                L.i("updateTemp: dat:3：" + data2);
                pushBeat();
                return;
            }
        }
    }

    /**
     * 串口回调实现
     *
     * @param type
     * @param serialPortData
     */

    public void doSerialPortData(String type, String serialPortData) {
        try {
            if (type.equals(Type_Chshopzl) || type.equals(Type_Chshopzl_OLD)) {
                L.i("Type_Chshopzl==" + type);
                ShopChUtils.setPutflag(false);

//                if (isMQTTshop){
//                    serialList.add(serialPortData);
//                    todoPageAty();
//                }
                return;
            }
            if (type.equals(Type_Lockopen)) {
                LockOpenDoor(serialPortData);
                return;
            }

            if (type.equals(Type_Lockclose)) {
                LockCloseDoor(serialPortData);
                return;
            }
            if (type.equals(Type_Steal)) {
                sendSteal(serialPortData);
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            L.i("updateTemp: " + e);
        }
    }

    List<String> serialList = new ArrayList<>();

    public void todoPageAty() {
        L.i(" 计时  出货数量--", countNum);
        if (countNum <= 0) {
//            if (timer != null) {
//                timer.cancel();
//            }
            if (serialList.size() > 0) {
                for (int i = 0; i < serialList.size(); i++) {
                    ShopInfoUtils.analyzeSlot(serialList.get(i), i, serialList.size(), 0);
                }
                ShopInfoUtils.sendCheckoutnotify("");
            }
            countNum = 0;
            serialList.clear();
            SystemClock.sleep(500);
            HashMap<String, Object> map = new HashMap<>();
            map.put("OrderNo", "");
            map.put("IsEnd", true);
            map.put("Remark", "完成");
            MchApiHttp.getOrderIsEnd(baseView, map);
        }
    }
}
